//
//  ShowAddViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/20.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "ShowAddViewController.h"
#import "BRPlaceholderTextView.h"
#import "KGModal.h"

@interface ShowAddViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UITextViewDelegate,UITextFieldDelegate,UINavigationControllerDelegate>

@property(nonatomic,weak) IBOutlet UITableView *listVIew;

@property(nonatomic,weak) UITextField *titleField;
@property(nonatomic,weak) BRPlaceholderTextView *contentView;
@property(nonatomic,weak) UISegmentedControl *genderControl;
@property(nonatomic,weak) UIButton *hairTypeButton;

@property(nonatomic,weak) UIButton *mainPicButton;
@property(nonatomic,weak) UIButton *sidePicButton;
@property(nonatomic,weak) UIButton *backPicButton;
@property(nonatomic,weak) UIButton *otherPicButton;

@property(nonatomic,weak) UIImageView *mainPicImage;
@property(nonatomic,weak) UIImageView *sidePicImage;
@property(nonatomic,weak) UIImageView *backPicImage;
@property(nonatomic,weak) UIImageView *otherPicImage;

@property(nonatomic,strong) NSData *mainPicImageData;
@property(nonatomic,strong) NSData *sidePicImageData;
@property(nonatomic,strong) NSData *backPicImageData;
@property(nonatomic,strong) NSData *otherPicImageData;

//for cache
typedef enum
{
    EImageTagMain = 1,
    EImageTagSide,
    EImageTagBack,
    EImageTagOther,
}ImageTag;
@property(nonatomic,assign) ImageTag myImageTag;

typedef enum
{
    SheetTagPhoto = 1,
    SheetTagType,
}SheetTag;
@property(nonatomic,assign) SheetTag mySheetTag;
@property(nonatomic,weak) UIButton *nextButton;
-(void)nextPressed:(id)sender;

@end

@implementation ShowAddViewController

@synthesize titleField,contentView,genderControl,hairTypeButton;
@synthesize mainPicButton,sidePicButton,backPicButton,otherPicButton;
@synthesize nextButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"创建晒单";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.mainPicImageData = nil;
        self.sidePicImageData = nil;
        self.backPicImageData = nil;
        self.otherPicImageData = nil;
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)backButtonPressed:(id)sender
{
    //    APPALL.needAutoLogin = 0;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 7;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            return 184.0f;
        case 1:
            return 84.0f;
        case 2:
            return 160.0f;
        case 3:
            return 160.0f;
        case 4:
            return 160.0f;
        case 5:
            return 160.0f;
        case 6:
            return 60.0f;
        default:
            return 0.0f;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    static NSString *inde;
    switch (indexPath.row) {
        case 0:
        {
            inde = @"showtitleid";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowTitleCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            self.titleField = (UITextField*)[cell viewWithTag:1];
            self.contentView = (BRPlaceholderTextView*)[cell viewWithTag:2];
            self.contentView.placeholder = @"请输入正文内容";
        }
            break;
        case 1:
        {
            inde = @"ShowGenderID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowGenderCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            if(!self.genderControl)
            {
                self.genderControl = (UISegmentedControl*)[cell viewWithTag:1];
                [self.genderControl addTarget:self
                                        action:@selector(genderChanged:)
                              forControlEvents:UIControlEventValueChanged];
            }
            if(!self.hairTypeButton)
            {
                self.hairTypeButton = (UIButton*)[cell viewWithTag:2];
                [self.hairTypeButton addTarget:self
                                       action:@selector(hairTypePressed:)
                             forControlEvents:UIControlEventTouchUpInside];
            }
        }
            break;
        case 2:{
            inde = @"ShowPicCell";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowPicCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *titleLabel = (UILabel*)[cell viewWithTag:1];
            self.mainPicButton = (UIButton*)[cell viewWithTag:2];
            self.mainPicImage = (UIImageView*)[cell viewWithTag:3];
            titleLabel.text = @"主图片:";
            [self.mainPicButton setTitle:[NSString stringWithFormat:@"%d",EImageTagMain] forState:UIControlStateDisabled];
            [self.mainPicButton addTarget:self action:@selector(ImageSelect:) forControlEvents:UIControlEventTouchUpInside];
            if(!self.mainPicImageData)
            {
                [self.mainPicImage setImage:[UIImage imageNamed:@"default_photo.png"]];
            }
        }
            break;
        case 3:{
            inde = @"ShowPicCell";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowPicCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *titleLabel = (UILabel*)[cell viewWithTag:1];
            self.sidePicButton = (UIButton*)[cell viewWithTag:2];
            self.sidePicImage = (UIImageView*)[cell viewWithTag:3];
            titleLabel.text = @"侧面图片:";
            [self.sidePicButton setTitle:[NSString stringWithFormat:@"%d",EImageTagSide] forState:UIControlStateDisabled];
            [self.sidePicButton addTarget:self action:@selector(ImageSelect:) forControlEvents:UIControlEventTouchUpInside];
            if(!self.sidePicImageData)
            {
                [self.sidePicImage setImage:[UIImage imageNamed:@"default_photo.png"]];
            }
        }
            break;
        case 4:{
            inde = @"ShowPicCell";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowPicCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *titleLabel = (UILabel*)[cell viewWithTag:1];
            self.backPicButton = (UIButton*)[cell viewWithTag:2];
            self.backPicImage = (UIImageView*)[cell viewWithTag:3];
            titleLabel.text = @"背面图片:";
            [self.backPicButton setTitle:[NSString stringWithFormat:@"%d",EImageTagBack] forState:UIControlStateDisabled];
            [self.backPicButton addTarget:self action:@selector(ImageSelect:) forControlEvents:UIControlEventTouchUpInside];
            if(!self.backPicImageData)
            {
                [self.backPicImage setImage:[UIImage imageNamed:@"default_photo.png"]];
            }
        }
            break;
        case 5:{
            inde = @"ShowPicCell";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowPicCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *titleLabel = (UILabel*)[cell viewWithTag:1];
            self.otherPicButton = (UIButton*)[cell viewWithTag:2];
            self.otherPicImage = (UIImageView*)[cell viewWithTag:3];
            titleLabel.text = @"其他图片:";
            [self.otherPicButton setTitle:[NSString stringWithFormat:@"%d",EImageTagOther] forState:UIControlStateDisabled];
            [self.otherPicButton addTarget:self action:@selector(ImageSelect:) forControlEvents:UIControlEventTouchUpInside];
            if(!self.otherPicImageData)
            {
                [self.otherPicImage setImage:[UIImage imageNamed:@"default_photo.png"]];
            }
        }
            break;
        case 6:{
            inde = @"DDButtonID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UIButton *but = (UIButton*)[cell viewWithTag:1];
            [but setTitle:@"晒单" forState:UIControlStateNormal];
            [but addTarget:self action:@selector(nextPressed:) forControlEvents:UIControlEventTouchUpInside];
        }
            break;
        default:
            return nil;
    }
    return cell;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self resignAllTextField];
}

-(void)resignAllTextField
{
    if(self.titleField.isFirstResponder)
        [self.titleField resignFirstResponder];
    if(self.contentView.isFirstResponder)
        [self.contentView resignFirstResponder];
}

-(void)genderChanged:(id)sender
{
    if(![self.genderControl selectedSegmentIndex]){
        if([[self.hairTypeButton titleForState:UIControlStateNormal] isEqualToString:@"新娘"]){
            [self.hairTypeButton setTitle:@"长发" forState:UIControlStateNormal];
        }
    }
}

-(void)hairTypePressed:(id)sender
{
    NSLog(@"...");
    self.mySheetTag = SheetTagType;
    UIActionSheet *actionSheet;
    if([self.genderControl selectedSegmentIndex]){
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发型"
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"长发",@"中发",@"短发",@"直发",@"卷发",@"编发",@"潮流",@"明星",@"宴会",@"新娘",nil];
    }else{
        actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择发型"
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"长发",@"中发",@"短发",@"直发",@"卷发",@"编发",@"潮流",@"明星",@"宴会",nil];
    }
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

-(void)ImageSelect:(id)sender
{
    [self resignAllTextField];
    self.myImageTag = [[sender titleForState:UIControlStateDisabled] intValue];
    [self ImageSelectTrue:nil];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"...%d",buttonIndex);
    //    if(buttonIndex)
}

-(void)ImageSelectTrue:(id)sender
{
    [self resignAllTextField];
    self.mySheetTag = SheetTagPhoto;
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"立即拍照",@"从本地选", nil];
    [chooseImageSheet showInView:self.view];
}

#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (self.mySheetTag) {
        case SheetTagPhoto:
        {
            switch (buttonIndex) {
                case 0://Take picture
                {
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        [self takePhoto:NO];
                    }
                    else
                    {
                        NSLog(@"模拟器无法拍照");
                        [self takePhoto:YES];
                    }
                }
                    break;
                case 1://From album
                {
                    [self takePhoto:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case SheetTagType:{
            if(buttonIndex >= actionSheet.numberOfButtons - 1)
                break;
            [self.hairTypeButton setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];
        }
            break;
        default:
            break;
    }
}

-(void)takePhoto:(BOOL)localornot
{
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = localornot?UIImagePickerControllerSourceTypePhotoLibrary:UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:NO completion:^{
        NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        NSLog(@"mediaType:%@",mediaType);
        if ([mediaType isEqualToString:@"public.image"]){
            UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            if(originImage==nil) return;
            UIImage *rotatedImage = [tooles rotateImage:originImage];
            UIImage *scaleImage = [tooles scaleImage:rotatedImage];
            switch (self.myImageTag) {
                case EImageTagMain:
                {
                    [self.mainPicImage setImage:scaleImage];
                    self.mainPicImageData = UIImageJPEGRepresentation(scaleImage,0.4f);
                }
                    break;
                case EImageTagSide:
                {
                    [self.sidePicImage setImage:scaleImage];
                    self.sidePicImageData = UIImageJPEGRepresentation(scaleImage, 0.4f);
                }
                    break;
                case EImageTagBack:
                {
                    [self.backPicImage setImage:scaleImage];
                    self.backPicImageData = UIImageJPEGRepresentation(scaleImage, 0.4f);
                }
                    break;
                case EImageTagOther:
                {
                    [self.otherPicImage setImage:scaleImage];
                    self.otherPicImageData = UIImageJPEGRepresentation(scaleImage, 0.4f);
                }
                    break;
                default:
                    break;
            }
        }
    }];
}

-(void)nextPressed:(id)sender
{
    [self resignAllTextField];
    if(!self.mainPicImageData.length)
    {
        [SVProgressHUD showErrorWithStatus:@"没有上传主照片！"];
        return;
    }
    if(self.mainPicImageData.length > 5 * 1024 * 1024)
    {
        [SVProgressHUD showErrorWithStatus:@"正面照片过大，请重新拍照！"];
        return;
    }
    if(self.sidePicImageData.length > 5 * 1024 * 1024)
    {
        [SVProgressHUD showErrorWithStatus:@"侧面照片过大，请重新拍照！"];
        return;
    }
    if(self.backPicImageData.length > 5 * 1024 * 1024)
    {
        [SVProgressHUD showErrorWithStatus:@"背面照片过大，请重新拍照！"];
        return;
    }
    if(self.otherPicImageData.length > 5 * 1024 * 1024)
    {
        [SVProgressHUD showErrorWithStatus:@"次图过大，请重新拍照！"];
        return;
    }
    /*
     order - 订单id，可空。
     title - 晒单标题，字符串，可空。
     content - 晒单文本内容，字符串，可空。
     gender - 性别，取值【男/女】，必填。
     hairType - 发型，字符串，必填。字串内容必须在发型字典表中。
     mainPic - 晒单主图片，base64编码，必填。
     sidePic - 晒单侧面图，base64编码，可空。
     backPic - 晒单后面图，base64编码，可空。
     otherPic - 晒单其他图，base64编码，可空。
     */
    NSString *titleStr = [self.titleField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *contentStr = [self.contentView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if(titleStr.length > 16)
    {
        [SVProgressHUD showErrorWithStatus:@"标题不能超过16字"];
        return;
    }
    if(contentStr.length > 50)
    {
        [SVProgressHUD showErrorWithStatus:@"评论不能超过50字"];
        return;
    }
    NSString *mainStr = self.mainPicImageData?[self.mainPicImageData base64EncodedStringWithOptions:0]:@"";
    NSString *sideStr = self.sidePicImageData?[self.sidePicImageData base64EncodedStringWithOptions:0]:@"";
    NSString *backStr = self.backPicImageData?[self.backPicImageData base64EncodedStringWithOptions:0]:@"";
    NSString *otherStr = self.otherPicImageData?[self.otherPicImageData base64EncodedStringWithOptions:0]:@"";
//    NSLog(@"%@",mainStr);
    NSDictionary *para =
    @{@"order":@"",
      @"title":titleStr,
      @"content":contentStr,
      @"gender":self.genderControl.selectedSegmentIndex?@"女":@"男",
      @"hairType":[self.hairTypeButton titleForState:UIControlStateNormal],
      @"mainPic":mainStr,
      @"sidePic":sideStr,
      @"backPic":backStr,
      @"otherPic":otherStr,
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
#if 1
    //你的接口地址
    ///////////////////////////////////////////////////////////////
    NSString *url=[NSString stringWithFormat:@"%@show/create",APPALL.globalUrl];
    //发送请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@",responseObject);
        int succInt = [[(NSDictionary*)responseObject valueForKey:@"success"] intValue];
        if(succInt){
            [self.delegate addFinished:nil];
        }else{
            [tooles showGlobalAlertWithTitle:@"" andMsg:[(NSDictionary*)responseObject valueForKey:@"code"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        }
        [SVProgressHUD dismiss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [tooles showGlobalAlertWithTitle:@"" andMsg:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }];
    ///////////////////////////////////////////////////////////////////////
#else
    [AVCloud callFunctionInBackground:@"show_create" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
#endif
}


-(void)dealloc
{
    self.mainPicImageData = nil;
    self.sidePicImageData = nil;
    self.backPicImageData = nil;
    self.otherPicImageData = nil;
}

@end